package com.bell.atensettings.settingDetails;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import static android.net.wifi.WifiConfiguration.INVALID_NETWORK_ID;
import com.android.internal.util.AsyncChannel;
import com.bell.atensettings.R;
import com.bell.atensettings.SystemApplication;
import com.bell.atensettings.bean.AccessPoint;
import com.bell.atensettings.bean.AccessPointBean;
import com.bell.atensettings.widgets.ProgressDialog;
import com.bell.atensettings.widgets.SwitchButton;
import com.bell.atensettings.wifi.WifiDialog;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.DetailedState;
import android.net.ethernet.EthernetManager;
import android.net.wifi.ScanResult;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
import android.net.wifi.WifiConfiguration.GroupCipher;
import android.net.wifi.WifiConfiguration.Protocol;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WpsResult;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class WifiSettings extends Activity implements OnItemClickListener, OnClickListener
{
    private static final int WIFI_RESCAN_INTERVAL_MS = 10 * 1000;
    static final int SECURITY_NONE = 0;
    static final int SECURITY_WEP = 1;
    static final int SECURITY_PSK = 2;
    static final int SECURITY_EAP = 3;
    
    private static final int WIFI_DIALOG_ID = 1;
    private static final int WPS_PBC_DIALOG_ID = 2;
    private static final int WPS_PIN_DIALOG_ID = 3;
    private static final int WIFI_SKIPPED_DIALOG_ID = 4;
    private static final int WIFI_AND_MOBILE_SKIPPED_DIALOG_ID = 5;

    static final int RESULT_CONNECT = 0;// 连接
    static final int RESULT_DISCONNECT = 1;// 取消保存
    static final int RESULT_CANCEL = 2;// 取消

    private Context mContext;
    private IntentFilter mFilter;
    private Scanner mScanner;

    private WifiManager mWifiManager;
    private AccessPoint mSelectedAccessPoint = null;
    private AccessPoint mDlgAccessPoint;
    private WifiManager.ActionListener mConnectListener;
    private WifiManager.ActionListener mSaveListener;
    private WifiManager.ActionListener mForgetListener;

    private DetailedState mLastState;
    private WifiInfo mLastInfo;

    private AtomicBoolean mConnected = new AtomicBoolean(false);

    private ArrayList<AccessPoint> _mItem;
    private TextView tv_flag;
    private SwitchButton iv_flag;
    private TextView tv_status;
    private ListView mListView;
    private ItemAdapter itemAdapter;
    private LayoutInflater layoutInflater;
    private Dialog mDialog;
    private ProgressDialog mProgDialog;
    private int index = 0;
    private int mRssi;
    private int security;
    private boolean wifiTag;
    private boolean wpsAvailable;
    PskType pskType;
    private BroadcastReceiver mReceiver;

    enum PskType
    {
        UNKNOWN, WPA, WPA2, WPA_WPA2
    }

    public WifiSettings() {
        wifiTag = false;
        index = 0;
        layoutInflater = null;
        pskType = PskType.UNKNOWN;
        wpsAvailable = false;
        mConnected = new AtomicBoolean(false);
    }

    private void init()
    {
        mFilter = new IntentFilter();
        mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        mFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
        mFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        mFilter.addAction(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
        mFilter.addAction(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION);
        mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
        // mFilter.addAction(WifiManager.ERROR_ACTION);

        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent)
            {
                handleEvent(context, intent);
            }
        };
        mScanner = new Scanner();
        registerReceiver(mReceiver, mFilter);
    }

    private void handleEvent(Context context, Intent intent)
    {
        String action = intent.getAction();
        if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
            updateWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN));
            // updateAccessPoints();
        } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)
                || WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION.equals(action)
                || WifiManager.LINK_CONFIGURATION_CHANGED_ACTION.equals(action)) {
            updateAccessPoints();
        } else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) {
            SupplicantState supplicantstate = (SupplicantState) intent.getParcelableExtra("newState");
            if (!mConnected.get() && SupplicantState.isHandshakeState(supplicantstate))
                updateConnectionState(WifiInfo.getDetailedStateOf(supplicantstate));
        } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
            NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            mConnected.set(info.isConnected());
            updateAccessPoints();
            updateConnectionState(info.getDetailedState());
        } else if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) {
            updateConnectionState(null);
        }
        // else if (WifiManager.ERROR_ACTION.equals(action))
        // {
        // int errorCode = intent.getIntExtra(WifiManager.EXTRA_ERROR_CODE, 0);
        // switch (errorCode)
        // {
        // case WifiManager.WPS_OVERLAP_ERROR:
        // Toast.makeText(context, "WPS_OVERLAP_ERROR", 0).show();
        // break;
        // }
        // tv_status.setText("验证失败！");
        // }
    }

    private void updateAccessPoints()
    {
        final int wifiState = mWifiManager.getWifiState();

        switch (wifiState) {
            case WifiManager.WIFI_STATE_ENABLED:
                _mItem = constructAccessPoints();
                if (itemAdapter != null) {
                    itemAdapter.setAccessPointItem(_mItem);
                }
                if (mDialog.isShowing() && mDialog != null) {
                    mDialog.dismiss();
                }
                tv_status.setText("未连接");
                break;

            case WifiManager.WIFI_STATE_ENABLING:
                tv_status.setText("正在开启网络……");
                break;

            case WifiManager.WIFI_STATE_DISABLING:
                _mItem = new ArrayList<AccessPoint>();
                index = 0;

                if (itemAdapter != null) {
                    itemAdapter.setAccessPointItem(_mItem);
                }
                tv_status.setText("正在关闭网络……");
                break;

            case WifiManager.WIFI_STATE_DISABLED:
                if (mDialog.isShowing() && mDialog != null) {
                    mDialog.dismiss();
                }
                tv_status.setText("未开启");
                break;
            default:
                _mItem = constructAccessPoints();
                if (itemAdapter != null) {
                    itemAdapter.setAccessPointItem(_mItem);
                }
        }
        refresh();
    }

    private void updateConnectionState(DetailedState state)
    {
        if (!mWifiManager.isWifiEnabled()) {
            mScanner.pause();
            return;
        }

        if (state == DetailedState.OBTAINING_IPADDR) {
            mScanner.pause();
        } else {
            mScanner.resume();
        }

        mLastInfo = mWifiManager.getConnectionInfo();

        if (state != null) {
            mLastState = state;
        }

        for (int i = _mItem.size() - 1; i >= 0; --i) {
            _mItem.get(i).update(mLastInfo, mLastState);
        }
        refresh();
    }

    private void refresh()
    {
        itemAdapter.notifyDataSetChanged();
    }

    private ArrayList<AccessPoint> constructAccessPoints()
    {
        ArrayList<AccessPoint> accessPoints = new ArrayList<AccessPoint>();
        Multimap<String, AccessPoint> multimap = new Multimap<String, AccessPoint>();
        final List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();

        if (configs != null) {
            for (WifiConfiguration config : configs) {
                AccessPoint accessPoint = new AccessPoint(this, config);
                accessPoint.update(mLastInfo, mLastState);
                accessPoints.add(accessPoint);
                multimap.put(accessPoint.ssid, accessPoint);
            }

        }

        final List<ScanResult> scanList = mWifiManager.getScanResults();

        if (scanList != null) {
            for (ScanResult results : scanList) {
                if (TextUtils.isEmpty(results.SSID) || results.capabilities.contains("[IBSS]"))
                    continue;

                boolean found = false;
                for (AccessPoint pointBean : multimap.getAll(results.SSID)) {
                    if (pointBean.update(results)) 
                        found = true;
                }

                if (!found) {
                    AccessPoint accessPointBean = new AccessPoint(this, results);
                    accessPoints.add(accessPointBean);
                    multimap.put(accessPointBean.ssid, accessPointBean);
                }
            }
        }

         Collections.sort(accessPoints);
        return accessPoints;
    }

    private void updateWifiState(int state)
    {
        invalidateOptionsMenu();

        switch (state) {
            case WifiManager.WIFI_STATE_ENABLED:
                mScanner.resume();
                if (mDialog.isShowing() && mDialog != null) {
                    mDialog.dismiss();
                }
                return;

            case WifiManager.WIFI_STATE_ENABLING:
                // addMessagePreference(R.string.wifi_starting);
                break;

            case WifiManager.WIFI_STATE_DISABLED:
                // addMessagePreference(R.string.wifi_empty_list_wifi_off);
                if (mDialog.isShowing() && mDialog != null) {
                    mDialog.dismiss();
                }
                tv_status.setText("未开启");
                break;
        }

        mLastInfo = null;
        mLastState = null;
        mScanner.pause();
    }

    static String convertToQuotedString(String s)
    {
        return (new StringBuilder()).append("\"").append(s).append("\"").toString();
    }

    static String removeDoubleQuotes(String s)
    {
        int i = s.length();

        if (i > 1 && s.charAt(0) == '"' && s.charAt(i - 1) == '"')
            s = s.substring(1, i - 1);
        return s;
    }

    private void initListView()
    {
        _mItem = new ArrayList<AccessPoint>();
        itemAdapter = new ItemAdapter(this, _mItem);

        mListView.setAdapter(itemAdapter);
        mListView.setOnItemClickListener(this);
    }

    private void initWifiListener()
    {
        mConnectListener = new WifiManager.ActionListener() {
            @Override
            public void onFailure(int i)
            {
                tv_status.setText(getResources().getString(R.string.valid_failed));
            }

            @Override
            public void onSuccess()
            {

            }
        };

        mSaveListener = new WifiManager.ActionListener() {

            @Override
            public void onSuccess()
            {

            }

            @Override
            public void onFailure(int i)
            {
                tv_status.setText(getResources().getString(R.string.valid_failed));
            }
        };

        mForgetListener = new WifiManager.ActionListener() {

            @Override
            public void onSuccess()
            {

            }

            @Override
            public void onFailure(int i)
            {
                tv_status.setText(getResources().getString(R.string.valid_failed));
            }
        };
    }

    /**
     * 检测无线网络是否开启
     * 
     * @return TRUE 开启否则关闭
     */
    private boolean checkWifiState()
    {
        final int wifiState = mWifiManager.getWifiState();
        boolean isEnabled = wifiState == WifiManager.WIFI_STATE_ENABLED;
        boolean isDisabled = wifiState == WifiManager.WIFI_STATE_DISABLED;

        if (isDisabled || isEnabled)
            iv_flag.setEnabled(isEnabled || isDisabled);
        else
            iv_flag.setEnabled(true);
        return isEnabled;
    }

    protected WifiConfiguration generateOpenNetworkConfig(AccessPoint item)
    {
        if (security != 0) {
            throw new IllegalStateException();
        } else {
            WifiConfiguration wifiConfiguration = new WifiConfiguration();
            wifiConfiguration.SSID = convertToQuotedString(item.ssid);
            wifiConfiguration.allowedKeyManagement.set(KeyMgmt.NONE);
            return wifiConfiguration;
        }
    }

    private void initView()
    {
        initListView();
        if (checkWifiState()) {
            mProgDialog.setMessage(getResources().getString(R.string.find_wifi));
            mDialog = mProgDialog.createLoadingDialog(this);
            mDialog.show();
            iv_flag.setChecked(true);
            wifiTag = true;
        } else {
            tv_status.setText("未开启");
            iv_flag.setChecked(false);
            wifiTag = false;
        }

        iv_flag.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton button, boolean checked)
            {
                wifiTag = checked;
                if (wifiTag) {
                    mProgDialog.setMessage(getResources().getString(R.string.open_wifi));
                    mDialog = mProgDialog.createLoadingDialog(WifiSettings.this);
                    mDialog.show();
                    mWifiManager.setWifiEnabled(wifiTag);
                } else {
                    mProgDialog.setMessage(getResources().getString(R.string.close_wifi));
                    mDialog = mProgDialog.createLoadingDialog(WifiSettings.this);
                    mDialog.show();
                    mWifiManager.setWifiEnabled(wifiTag);
                }
            }
        });
    }

    private WifiConfiguration getconfig(Intent data)
    {
        String password = data.getStringExtra("password");
        WifiConfiguration config = new WifiConfiguration();

        if (mSelectedAccessPoint.getNetworkId() == INVALID_NETWORK_ID) {
            config.SSID = convertToQuotedString(mSelectedAccessPoint.ssid);
        } else {
            config.networkId = mSelectedAccessPoint.getNetworkId();
        }
        config.BSSID = mSelectedAccessPoint.getBssid();

        Log.i("tv_status", getResources().getString(R.string.connect_wifi));
        tv_status.setText(getResources().getString(R.string.connect_wifi));
        SystemApplication.setWifiPWD(mSelectedAccessPoint.ssid, data.getStringExtra("password"));
        switch (mSelectedAccessPoint.getSecurity()) {
            case SECURITY_NONE:
                config.allowedKeyManagement.set(KeyMgmt.NONE);
                break;
            case SECURITY_WEP:
                config.allowedKeyManagement.set(KeyMgmt.NONE);
                config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
                config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
                if (password.length() != 0) {
                    int length = password.length();
                    // WEP-40, WEP-104, and 256-bit WEP (WEP-232?)
                    if ((length == 10 || length == 26 || length == 58) && password.matches("[0-9A-Fa-f]*")) {
                        config.wepKeys[0] = password;
                    } else {
                        config.wepKeys[0] = '"' + password + '"';
                    }
                }
                break;
            case SECURITY_PSK:
                config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);

                if (password.length() > 0) {
                    if (password.matches("[0-9A-Fa-f]{64}")) {
                        config.preSharedKey = password;
                    } else {
                        config.preSharedKey = '"' + password + '"';
                    }
                }

                break;
            case SECURITY_EAP:
                config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
                config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
                config.allowedAuthAlgorithms.set(AuthAlgorithm.LEAP);
                config.password.setValue(data.getStringExtra("password"));
                config.preSharedKey = convertToQuotedString(data.getStringExtra("password"));
                break;
            default:

                break;
        }
        config.proxySettings = WifiConfiguration.ProxySettings.UNASSIGNED;
        config.ipAssignment = WifiConfiguration.IpAssignment.UNASSIGNED;
        return config;
    }

    @Override
    protected void onCreate(Bundle bundle)
    {
        super.onCreate(bundle);
        setContentView(R.layout.wifi_settings);

        mContext = this;
        mProgDialog = new ProgressDialog();
        mDialog = mProgDialog.createLoadingDialog(this);
        tv_status = (TextView) findViewById(R.id.tv_status);
        tv_flag = (TextView) findViewById(R.id.tv);
        iv_flag = (SwitchButton) findViewById(R.id.on_off);
        mListView = (ListView) findViewById(R.id.listview);

        tv_status.setText("未连接");
        tv_flag.setText("\u65E0\u7EBF\u7F51\u7EDC");
        mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

        initWifiListener();
        initView();
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
    }

    @Override
    public void onBackPressed()
    {
        super.onBackPressed();

        overridePendingTransition(R.anim.start, R.anim.push_left_out);
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        unregisterReceiver(mReceiver);
        mScanner.pause();
    }

    protected Dialog onCreateDialog(int dialogId)
    {
        if (dialogId == WIFI_DIALOG_ID) {
            mDialog = new WifiDialog(this, this, mSelectedAccessPoint, false);
            return mDialog;
        }
        return super.onCreateDialog(dialogId);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        init();
        updateAccessPoints();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        switch (resultCode) {
            case RESULT_CONNECT:
                if (data == null)
                    return;
                WifiConfiguration tempConfig = isExsits(mSelectedAccessPoint.ssid);

                if (tempConfig != null) {
                    mWifiManager.connect(tempConfig.networkId, mConnectListener);
                } else {
                    submit(getconfig(data));
                }
                break;
            case RESULT_DISCONNECT:
                forget();
                break;
            case RESULT_CANCEL:
                break;
            default:
                break;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle bundle)
    {
        super.onSaveInstanceState(bundle);
    }

    private class Scanner extends Handler
    {
        private int mRetry = 0;

        void resume()
        {
            if (!hasMessages(0)) {
                sendEmptyMessage(0);
            }
        }

        void forceScan()
        {
            removeMessages(0);
            sendEmptyMessage(0);
        }

        void pause()
        {
            mRetry = 0;
            removeMessages(0);
        }

        @Override
        public void handleMessage(Message message)
        {
            if (mWifiManager.startScanActive()) {
                mRetry = 0;
            } else if (++mRetry >= 3) {
                mRetry = 0;
                Toast.makeText(WifiSettings.this, "", Toast.LENGTH_LONG).show();
                return;
            }
            sendEmptyMessageDelayed(0, WIFI_RESCAN_INTERVAL_MS);
        }
    }

    private class WifiServiceHandler extends Handler
    {

        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what) {
                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED:
                    if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
                        // AsyncChannel in msg.obj
                    } else {
                        // AsyncChannel set up failure, ignore
                        Log.e("WifiSettings", "Failed to establish AsyncChannel connection");
                    }
                    break;
                case WifiManager.ERROR:// WifiManager.CMD_WPS_COMPLETED:
                    WpsResult result = (WpsResult) msg.obj;
                    if (result == null)
                        break;
                    AlertDialog.Builder dialog = new AlertDialog.Builder(mContext).setTitle("wps").setPositiveButton(
                            android.R.string.ok, null);
                    switch (result.status) {
                        case FAILURE:
                            dialog.setMessage("wps failed");
                            dialog.show();
                            break;
                        case IN_PROGRESS:
                            dialog.setMessage("in progress");
                            dialog.show();
                            break;
                        default:
                            if (result.pin != null) {
                                dialog.setMessage((new StringBuffer()).append("ping output").append(result.pin)
                                        .toString());
                                dialog.show();
                            }
                            break;
                    }
                    break;
                // TODO: more connectivity feedback
                default:
                    // Ignore
                    break;
            }
        }
    }

    /** A restricted multimap for use in constructAccessPoints */
    private class Multimap<K, V>
    {
        private HashMap<K, List<V>> store = new HashMap<K, List<V>>();

        /** retrieve a non-null list of values with key K */
        List<V> getAll(K key)
        {
            List<V> values = store.get(key);
            return values != null ? values : Collections.<V> emptyList();
        }

        void put(K key, V val)
        {
            List<V> curVals = store.get(key);
            if (curVals == null) {
                curVals = new ArrayList<V>(3);
                store.put(key, curVals);
            }
            curVals.add(val);
        }
    }

    public class ItemAdapter extends BaseAdapter
    {
        private Context mContext;
        private ArrayList<AccessPoint> mItem = new ArrayList<AccessPoint>();

        public ItemAdapter(Context context, ArrayList<AccessPoint> arraylist) {
            mContext = context;
            mItem = arraylist;
        }

        public void setAccessPointItem(ArrayList<AccessPoint> apItems)
        {
            mItem = apItems;
        }

        public int getCount()
        {
            return mItem.size();
        }

        public Object getItem(int position)
        {
            return mItem.get(position);
        }

        public long getItemId(int position)
        {
            return (long) position;
        }

        public View getView(int position, View view, ViewGroup viewgroup)
        {
            ImageView imageview2;
            TextView textview;
            TextView text_status;
            ImageView imageview1;
            AccessPoint accesspointdetails = (AccessPoint) mItem.get(position);

            if (view == null) {
                view = ((LayoutInflater) mContext.getSystemService("layout_inflater")).inflate(R.layout.list_wifi_item,
                        null);
            }

            ImageView imageview = (ImageView) view.findViewById(R.id.iv_sign);
            if (mWifiManager.getConnectionInfo() != null && mWifiManager.getConnectionInfo().getSSID() != null) {
                if (accesspointdetails.getState() == DetailedState.CONNECTED) {
                    tv_status.setText("已连接-" + accesspointdetails.ssid);
                    imageview.setImageResource(R.drawable.choose_icon);
                } else {
                    imageview.setImageResource(R.drawable.extends_sign);
                }
            } else {
                imageview.setImageResource(R.drawable.extends_sign);
            }
            textview = (TextView) view.findViewById(R.id.tv_data);
            text_status = (TextView) view.findViewById(R.id.tv_status);
            imageview1 = (ImageView) view.findViewById(R.id.iv_lock);
            imageview2 = (ImageView) view.findViewById(R.id.iv_signal);

            textview.setText(accesspointdetails.ssid);
            text_status.setText(accesspointdetails.getmSummary());
            if (accesspointdetails.getSecurity() != 0) {
                imageview1.setVisibility(View.VISIBLE);
            } else {
                imageview1.setVisibility(View.INVISIBLE);
            }

            final int signal = accesspointdetails.getLevel();

            switch (signal) {
                case -1://信号不在范围内，不显示
                    imageview2.setImageDrawable(null);
                    break;
                case 0:
                    imageview2.setImageResource(R.drawable.wifi_0);
                    break;
                case 1:
                    imageview2.setImageResource(R.drawable.wifi_1);
                    break;
                case 2:
                    imageview2.setImageResource(R.drawable.wifi_2);
                    break;
                case 3:
                    imageview2.setImageResource(R.drawable.wifi_3);
                    break;
                default:
                    break;
            }
            imageview.setScaleType(android.widget.ImageView.ScaleType.FIT_XY);
            return view;
        }
    }

    private WifiConfiguration isExsits(String ssid)
    {
        for (WifiConfiguration configuration : mWifiManager.getConfiguredNetworks()) {
            if (configuration.SSID.equals(convertToQuotedString(ssid)))
                return configuration;
        }
        return null;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        final AccessPoint item = (AccessPoint) parent.getAdapter().getItem(position);
        final WifiConfiguration wifiConfiguration = isExsits(item.ssid);
        index = position;
        mSelectedAccessPoint = item;
        
        if (mDialog != null && mDialog.isShowing()) {
            removeDialog(WIFI_DIALOG_ID);
            mDialog = null;
        }

        if (mWifiManager.getConnectionInfo() != null && mWifiManager.getConnectionInfo().getSSID() != null
                && item.getState() == DetailedState.CONNECTED) {
            // 当前wifi已经连接，显示详细信息
            showDialog(WIFI_DIALOG_ID);
        } else {
            if (item.getSecurity() == SECURITY_NONE) {
                mProgDialog.setMessage(getResources().getString(R.string.connect_wifi));
                mDialog = mProgDialog.createLoadingDialog(mContext);
                mDialog.show();
                tv_status.setText(getResources().getString(R.string.connect_wifi));
                if (item.getNetworkId() == -1 && item.getSecurity() == SECURITY_NONE) {
                    item.generateOpenNetworkConfig();
                    mWifiManager.connect(mSelectedAccessPoint.getConfig(), mConnectListener);
                } else {
                    if (item.getSecurity() == SECURITY_NONE) {
                        mWifiManager.connect(mSelectedAccessPoint.getNetworkId(), mConnectListener);
                    }
                }
            } else if (isExsits(item.ssid) != null) {
                showDialog(WIFI_DIALOG_ID);
                //mWifiManager.connect(mSelectedAccessPoint.getConfig(), mConnectListener);
            } else {
                Intent intent = new Intent(mContext, WifiDetailSettings.class);

                intent.putExtra("ssid", mSelectedAccessPoint.ssid);
                startActivityForResult(intent, 1);
            }
        }
        overridePendingTransition(R.anim.push_left_in, R.anim.end);
    }

    void submit(WifiConfiguration config)
    {
        Log.i("tv_status", getResources().getString(R.string.connect_wifi));
        tv_status.setText(getResources().getString(R.string.connect_wifi));

        if (config == null) {
            if (mSelectedAccessPoint != null && mSelectedAccessPoint.getNetworkId() != -1) {
                mWifiManager.connect(mSelectedAccessPoint.getNetworkId(), mConnectListener);
            }
        } else {
            if (config.networkId != -1) {
                if (mSelectedAccessPoint != null)
                    mWifiManager.save(config, mSaveListener);
            }
            mWifiManager.connect(config, mConnectListener);
        }

        if (mWifiManager.isWifiEnabled()) {
            mScanner.resume();
        }
        updateAccessPoints();
    }

    private void saveNetwork(WifiConfiguration config)
    {
        mWifiManager.save(config, mSaveListener);
    }

    void forget()
    {
        try {
            mWifiManager.forget(mSelectedAccessPoint.getNetworkId(), mForgetListener);

            if (mWifiManager.isWifiEnabled()) {
                mScanner.resume();
            }
            updateAccessPoints();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    @Override
    public void onClick(DialogInterface dialogInterface, int button)
    {
        if (button == WifiDialog.BUTTON_FORGET && mSelectedAccessPoint != null) {
            forget();
        } else if (button == WifiDialog.BUTTON_SUBMIT && mSelectedAccessPoint != null) {
            submit(mSelectedAccessPoint.getConfig());
        }
    }
}
